package tree.tree2.symmetry.leftLeaf;

import sun.reflect.generics.tree.Tree;
import tree.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @ClassName SumOfLeftLeaves
 * @Description TODO
 * @Author lenovo
 * @Date 2023-05-05 9:21
 * @Version 1.0
 * @Comment Magic. Do not touch.
 * If this comment is removed. the program will blow up
 */
public class SumOfLeftLeaves {

    /**
     * 输入: root = [3,9,20,null,null,15,7]
     * 输出: 24
     * 解释: 在这个二叉树中，有两个左叶子，分别是 9 和 15，所以返回 24
     *
     * @param root
     * @return
     */
    public int sumOfLeftLeaves(TreeNode root) {
        int res = 0;
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size-- > 0) {

                TreeNode poll = queue.poll();

                if (poll.left != null) {
                    queue.add(poll.left);
                }

                if (poll.left != null && poll.left.left == null && poll.left.right == null) {
                    res += poll.left.val;
                }

                if (poll.right != null) {
                    queue.add(poll.right);
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(2);
        root.right.left = new TreeNode(1);
        SumOfLeftLeaves sumOfLeftLeaves = new SumOfLeftLeaves();
        System.out.println(sumOfLeftLeaves.sumOfLeftLeaves(root));
    }
}